package com.mxnet.chongjin.nci.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mxnet.chongjin.nci.R;
import com.mxnet.chongjin.nci.adapter.CauseAdapter;
import com.mxnet.chongjin.nci.base.BaseActivity;
import com.mxnet.chongjin.nci.bean.Cause;
import com.mxnet.chongjin.nci.bean.Moving;
import com.mxnet.chongjin.nci.config.Api;
import com.mxnet.chongjin.nci.receiver.HoneywellReceiver;
import com.mxnet.chongjin.nci.utils.StringUtils;
import com.mxnet.chongjin.nci.view.ItemInventoryView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class ManageOutInventoryActivity extends BaseActivity implements HoneywellReceiver.OnReceiveCode {
    private Context mContext;
    private Button mButtonClear, mButtonSave, mButtonQuit;
    private TextView mTextViewScanResult, mTextViewVolume, mTextViewScanCount;
    private EditText mTextViewStock, mEditTextTrays, mTextViewOrder;
    private ScrollView mScrollView;
    private int scanCount = 0;
    private Spinner mSpinnerCause;
    private List<Cause> mCauseList;
    private CauseAdapter mCauseAdapter;
    private LinearLayout mLayout;
    private ArrayList mBarcodeList;
    private List<String> mStockNoList;
    private SharedPreferences mPreferences;
    private List<Moving> mMovingList;

    private HoneywellReceiver mHoneywellReceiver = new HoneywellReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            super.onReceive(context, intent);
            if ((HoneywellReceiver.INTENT_SCAN_ACTION).equals(intent.getAction())) {
                final String data = StringUtils.replaceBlank(intent.getStringExtra("data"));
                if (!TextUtils.isEmpty(data)) {
                    mTextViewScanResult.setText("扫描成功");
                    mTextViewScanResult.setTextColor(Color.GREEN);
                    if (data.length() == 6) {
                        // 长度为6表示是库位
                        mTextViewStock.setText(data);
                    } else if (data.length() == 8) {
                        // 长度为8表示卷号
                        if (TextUtils.isEmpty(mTextViewStock.getText().toString())) {
                            StringUtils.vibrate1(mContext, StringUtils.short_mil_sec);
                            Toast.makeText(mContext, "请先扫描库位！", Toast.LENGTH_SHORT).show();
                        } else {
                            boolean b = false;
                            if (mBarcodeList.size() > 0) {
                                for (int k = 0; k < mBarcodeList.size(); k++) {
                                    if (mBarcodeList.get(k).equals(data)) {
                                        b = true;
                                        StringUtils.vibrate1(mContext, StringUtils.medimu_mil_sec);
                                        AlertDialog alertDialog1 = new AlertDialog.Builder(mContext)
                                                .setTitle("提示")//标题
                                                .setMessage("该卷号已存在")//内容
                                                .create();
                                        alertDialog1.show();
                                    }
                                }
                            }
                            if (!b) {
                                mTextViewVolume.setText(data);
                                mBarcodeList.add(data);
                                scanCount += 1;
                                mTextViewScanCount.setText(mBarcodeList.size() + "");
                                ItemInventoryView itemInventoryView = new ItemInventoryView(mContext, R.layout.item_inventory);
                                itemInventoryView.getTextView1().setText(mTextViewStock.getText().toString());
                                itemInventoryView.getTextView2().setText(data);
                                mLayout.addView(itemInventoryView, 0);
                                /*final ScrollView sv = mScrollView;
                                Handler handler = new Handler();
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        sv.fullScroll(ScrollView.FOCUS_DOWN);
                                    }
                                });*/
                            }
                        }
                    } else {
                        mTextViewScanResult.setText("无效的条码");
                        mTextViewScanResult.setTextColor(Color.RED);
                        StringUtils.vibrate1(mContext, StringUtils.short_mil_sec);
                    }
                } else {
                    mTextViewScanResult.setText("扫描异常");
                    mTextViewScanResult.setTextColor(Color.RED);
                    StringUtils.vibrate1(mContext, StringUtils.short_mil_sec);
                }
            }
        }
    };

    @Override
    public void notifyThread(Intent intent) {
        final String data = StringUtils.replaceBlank(intent.getStringExtra("data"));
        //        if (data.length() == 8) {
        //            OkHttpUtils.get()
        //                    .url(mPreferences.getString("URL_HEADER", "") + Api.BARCODE_QUERY_LOCATIONS)
        //                    .addParams("barcode", data)
        //                    .build()
        //                    .execute(new StringCallback() {
        //                        @Override
        //                        public void onError(Call call, Exception e, int id) {
        //                            Log.i("*****==onError==", e.getMessage());
        //                        }
        //
        //                        @Override
        //                        public void onResponse(String response, int id) {
        //                            if (!TextUtils.isEmpty(response)) {
        //                                try {
        //                                    JSONObject jsonObject = new JSONObject(response);
        //                                    boolean isSuccess = jsonObject.optBoolean("success");
        //                                    if (isSuccess) {
        //                                        JSONObject object = jsonObject.optJSONObject("data");
        ////                                        JSONArray datas = object.optJSONArray("locations");
        ////                                        String s = "";
        ////                                        for (int i = 0; i < datas.length(); i++) {
        ////                                            s += (datas.optJSONObject(i).optString("location") + ",");
        ////                                        }
        ////                                        s = s.substring(0, s.length() - 1);
        //                                        mEditTextTrays.setText(object.optString("locations"));
        //                                    }
        //                                } catch (Exception e) {
        //                                    e.printStackTrace();
        //                                }
        //                            }
        //                        }
        //                    });
        //        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mHoneywellReceiver, new IntentFilter(HoneywellReceiver.INTENT_SCAN_ACTION));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_out_inventory);
        mContext = ManageOutInventoryActivity.this;
        mPreferences = getPreferences();

        mCauseList = new ArrayList<>();
        mStockNoList = new ArrayList<>();
        mBarcodeList = new ArrayList<>();
        mMovingList = new ArrayList<>();

        mHoneywellReceiver.setOnReceiveCode(this);
        mScrollView = findViewById(R.id.view_manager_out_inventory_scrollView);
        mLayout = findViewById(R.id.ll_manage_out_inventory_list);


        mTextViewScanResult = findViewById(R.id.textview_manage_out_inventory_scan_result);

        mTextViewStock = findViewById(R.id.textview_manage_out_inventory_stock);

        mEditTextTrays = findViewById(R.id.edittext_manage_out_inventory_trays);

        mTextViewVolume = findViewById(R.id.textview_manage_out_inventory_volume);

        mTextViewScanCount = findViewById(R.id.textview_manage_out_inventory_scan_count);

        mTextViewOrder = findViewById(R.id.textview_manage_out_inventory_order);

        mSpinnerCause = findViewById(R.id.spinner_manage_out_inventory_cause);
        initLayout();
        initSpinner();

        mButtonClear = findViewById(R.id.btn_manege_out_inventory_clear);
        mButtonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog alertDialog1 = new AlertDialog.Builder(mContext)
                        .setTitle("温馨提示")//标题
                        .setMessage("确定要继续吗?")//内容
                        .setCancelable(true)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mSpinnerCause.setSelection(0);
                                mTextViewStock.setText("");
                                mTextViewVolume.setText("");
                                scanCount = 0;
                                mTextViewScanCount.setText(scanCount + "");
                                mLayout.removeAllViews();
                                mBarcodeList.clear();
                                mStockNoList.clear();
                                mMovingList.clear();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create();
                alertDialog1.show();


            }
        });

        mButtonSave = findViewById(R.id.btn_manege_out_inventory_save);
        mButtonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBarcodeList.size() == 0) {
                    Toast.makeText(mContext, "没有数据！", Toast.LENGTH_SHORT).show();
                    StringUtils.beep(mContext);
                } else {
                    // 创建临时单据
                    mMovingList.clear();
                    mBarcodeList.clear();
                    for (int j = 0; j < mLayout.getChildCount(); j++) {
                        Moving moving = new Moving();
                        moving.setLocationCode(((ItemInventoryView) mLayout.getChildAt(j)).getTextView1().getText().toString());
                        moving.setBarcode(((ItemInventoryView) mLayout.getChildAt(j)).getTextView2().getText().toString());
                        mBarcodeList.add(((ItemInventoryView) mLayout.getChildAt(j)).getTextView2().getText().toString());
                        mMovingList.add(moving);
                    }
                    String doc_no = StringUtils.getNumber(mPreferences, "OutInventory");
                    Log.i("doc_no", doc_no);
                    if (mSpinnerCause.getSelectedItemPosition() < 0) {
                        return;
                    }
                    OkHttpUtils.post()
                            .url(mPreferences.getString("URL_HEADER", "") + Api.CREATE_DOCUMENT)
                            .addParams("causeId", mCauseList.get(mSpinnerCause.getSelectedItemPosition()).getId() + "")
                            .addParams("docType", "03")
                            .addParams("inWay", "")
                            .addParams("deviceNo", mPreferences.getString("deviceNo", ""))
                            .addParams("details", new Gson().toJson(mMovingList))
                            .addParams("order", mTextViewOrder.getText().toString())
                            .addParams("doc_no", doc_no)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    Log.i("*****==onError==", e.getMessage());
                                    mTextViewScanResult.setText(e.getMessage());
                                    mTextViewScanResult.setTextColor(Color.RED);
                                    mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                    StringUtils.beep(mContext);
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    if (!TextUtils.isEmpty(response)) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response);
                                            boolean isSuccess = jsonObject.optBoolean("success");
                                            if (isSuccess) {
                                                // 跳转单据确认页面
                                                Toast.makeText(mContext, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                                                Intent intent = new Intent(mContext, ManageOutInventorySaveActivity.class);
                                                intent.putExtra("cause", mCauseList.get(mSpinnerCause.getSelectedItemPosition()));
                                                intent.putExtra("order", mTextViewOrder.getText());
                                                intent.putStringArrayListExtra("barcodeList", mBarcodeList);
                                                intent.putExtra("pickingId", jsonObject.optJSONObject("data").optInt("picking"));
                                                startActivityForResult(intent, 200);
                                            } else {
                                                Log.i("*****==onResponse==", response);
                                                mTextViewScanResult.setText(jsonObject.optString("message"));
                                                mTextViewScanResult.setTextColor(Color.RED);
                                                mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            });
                }
            }
        });

        mButtonQuit = findViewById(R.id.btn_manege_out_inventory_quit);
        mButtonQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, IndexActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
            }
        });
    }

    public void initLayout() {
        mMovingList.clear();
        mTextViewVolume.setText("");
        mLayout.removeAllViews();
        OkHttpUtils.get()
                .url(mPreferences.getString("URL_HEADER", "") + Api.GET_MOVINGS)
                .addParams("deviceNo", mPreferences.getString("deviceNo", ""))
                .addParams("docType", "03")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("*****==onError==", e.getMessage());
                        mTextViewScanResult.setText(e.getMessage());
                        mTextViewScanResult.setTextColor(Color.RED);
                        mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                        StringUtils.beep(mContext);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                boolean isSuccess = jsonObject.optBoolean("success");
                                int code = jsonObject.optInt("code");
                                if (isSuccess) {
                                    mBarcodeList.clear();
                                    if (code == 200) {
                                        JSONArray datas = jsonObject.optJSONArray("data");
                                        for (int k = 0; k < datas.length(); k++) {
                                            JSONObject object = datas.optJSONObject(k);
                                            Moving moving = new Moving();
                                            moving.setBarcode(object.optString("barcode"));
                                            moving.setLocationCode(object.optString("location"));
                                            mMovingList.add(moving);
                                            mBarcodeList.add(object.optString("barcode"));
                                            ItemInventoryView inventoryView = new ItemInventoryView(mContext, R.layout.item_inventory);
                                            inventoryView.getTextView1().setText(object.optString("location"));
                                            inventoryView.getTextView2().setText(object.optString("barcode"));
                                            mLayout.addView(inventoryView, 0);
                                        }
                                        mTextViewScanCount.setText(mBarcodeList.size() + "");
                                    } else {
                                        mTextViewScanCount.setText("0");

                                    }

                                } else {
                                    mTextViewScanResult.setText(jsonObject.optString("message"));
                                    mTextViewScanResult.setTextColor(Color.RED);
                                    mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                StringUtils.beep(mContext);
                            }
                        }
                    }
                });
    }

    public void initSpinner() {
        OkHttpUtils.get()
                .url(mPreferences.getString("URL_HEADER", "") + Api.GET_CAUSE)
                .addParams("type", "out")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("*****==onError==", e.getMessage());
                        mTextViewScanResult.setText(e.getMessage());
                        mTextViewScanResult.setTextColor(Color.RED);
                        mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                        StringUtils.beep(mContext);
                        Toast.makeText(mContext, "网络异常或信号不好，稍后再试", Toast.LENGTH_SHORT).show();
                        mButtonQuit.callOnClick();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                boolean isSuccess = jsonObject.optBoolean("success");
                                if (isSuccess) {
                                    JSONArray datas = jsonObject.optJSONArray("data");
                                    for (int i = 0; i < datas.length(); i++) {
                                        JSONObject object = datas.optJSONObject(i);
                                        Cause cause = new Cause();
                                        cause.setId(object.optInt("id"));
                                        cause.setDescribe(object.optString("describe"));
                                        mCauseList.add(cause);
                                    }
                                    mCauseAdapter = new CauseAdapter(mContext, mCauseList);
                                    mSpinnerCause.setAdapter(mCauseAdapter);
                                } else {
                                    mTextViewScanResult.setText(jsonObject.optString("message"));
                                    mTextViewScanResult.setTextColor(Color.RED);
                                    mTextViewScanResult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                StringUtils.beep(mContext);
                            }
                        }
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mHoneywellReceiver);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 201) {
            initLayout();
        }
    }
}
